package com.naiterui.ehp.ps.sms.factory;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.naiterui.ehp.ps.sms.enums.ChuanglanStatus;
import com.naiterui.ehp.ps.sms.exception.ExceptionCodes;
import com.naiterui.ehp.ps.sms.exception.SmsBusinessException;
import com.naiterui.ehp.ps.sms.vo.MessageResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author gaoliangliang
 * @date 2022/5/15
 * @since 0.0.1
 */
@Slf4j
public class ChuanglanSms {

    /**
     * 单条短信发送
     *
     * @param phone
     * @param content
     */
    public static MessageResponseVO singleSend(String phone, String content) throws SmsBusinessException {
        // 发送短信
        String result = ChuanglanApi.singleSend(phone, content);
        log.info("[发送短信，蓝创平台]--短信发送完成，手机号电话号码:[{}] 内容为:[{}] 第三方平台返回结果:[{}]", phone, content, result);
        return processApiResult(result);
    }

    /**
     * 处理API返回的结果
     *
     * @param result
     */
    private static MessageResponseVO processApiResult(String result) throws SmsBusinessException {
        // 处理api请求结果
        if (StringUtils.isBlank(result)) {
            log.error("蓝创平台返回结果为空：[{}]", result);
            throw new SmsBusinessException(ExceptionCodes.SMS_PLATFORM_RETURN_NULL);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        MessageResponseVO responseVO = new MessageResponseVO();
        String returnStatus = resultJson.getString("code");
        ChuanglanStatus chuanglanStatus = ChuanglanStatus.byCode(returnStatus);
        if (ChuanglanStatus.SUCCESS.equals(chuanglanStatus)) {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SUCCESS));
            responseVO.setStatusMsg("成功");
        } else {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SMS_PLATFORM_RETURN_ERROR));
            String errorMsg = resultJson.getString("errorMsg");
            responseVO.setStatusMsg(StrUtil.blankToDefault(errorMsg, chuanglanStatus.msg()));
        }
        return responseVO;
    }

}
